package shuishijie.suishijie.model.web;

import android.content.Context;
import android.util.Log;



import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import okhttp3.Authenticator;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import shuishijie.suishijie.model.EnvConfig;
import shuishijie.suishijie.util.WebUnit;


/**
 * RetrofitManager
 */
public class RetrofitManager {
    //地址
//    private String BaseURL = "http://cookbook.mindx.cn/";
    //private String BaseURL = EnvConfig.getServerUrl();
    private String BaseURL="https://offline.api.gvg666.com";

    //短缓存有效期为1分钟
    public static final int CACHE_STALE_SHORT = 60;
    //长缓存有效期为7天
    public static final int CACHE_STALE_LONG = 60 * 60 * 24 * 7;

    public static final String CACHE_CONTROL_AGE = "Cache-Control: public, max-age=";

    //查询缓存的Cache-Control设置，为if-only-cache时只查询缓存而不会请求服务器，max-stale可以配合设置缓存失效时间
    public static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_LONG;
    //查询网络的Cache-Control设置，头部Cache-Control设为max-age=0时则不会使用缓存而请求服务器
    public static final String CACHE_CONTROL_NETWORK = "max-age=0";
    private static OkHttpClient mOkHttpClient;
    private Retrofit mRetrofit;

    private static Context context = null;

    public static void init(Context context) {
        RetrofitManager.context = context.getApplicationContext();
    }

    /**
     * 构建Retrofit
     *
     * @return
     */
    public Retrofit build() {
        if (context == null) {
          //  Logger.e("Please init RetrofitManager with RetrofitManager.init(context)");
            return null;
        }
        initOkHttpClient();
        initRetrofit();
        return mRetrofit;
    }

    private RetrofitManager() {

    }

    static HashSet<String> cookies = new HashSet<>();

    public class ReadCookiesInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            for (String cookie : cookies) {
                builder.addHeader("Cookie", cookie);
                Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
            }

            return chain.proceed(builder.build());
        }
    }

    public class SaveCookiesInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());

            if (!originalResponse.headers("Set-Cookie").isEmpty()) {

                for (String header : originalResponse.headers("Set-Cookie")) {
                    cookies.add(header);
                }

            }

            return originalResponse;
        }
    }

    protected void initRetrofit() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BaseURL)
                .client(mOkHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

    }

    private void initOkHttpClient() {
        //拦截器，用于输出网络请求和结果的 Log
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //如果你需要在遇到诸如 401 Not Authorised 的时候进行刷新 token
        Authenticator mAuthenticator = (route, response) -> {

            String token = "";// ReadUserData.getUserToken(BaseApplication.context());

            return response.request().newBuilder()
                    .addHeader("Authorization", "Bearer" + " " + token)
                    .build();
        };
        //所有网络请求都附上你的拦截器
        Interceptor mTokenInterceptor = chain -> {
//            Request originalRequest = chain.request();
////                if (Your.sToken == null || alreadyHasAuthorizationHeader(originalRequest)) {
////                    return chain.proceed(originalRequest);
////                }
//            Request authorised = originalRequest.newBuilder()
//                    .header("Authorization", "Bearer" + " " + "")
//                    .build();
//            return chain.proceed(authorised);

            Request request = chain.request();
            if (!WebUnit.isNetworkAvailble(context)) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();

            }
            Response originalResponse = chain.proceed(request);

            if (WebUnit.isNetworkAvailble(context)) {
                //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                        .removeHeader("Pragma")
                        .build();
            }

        };


        if (mOkHttpClient == null) {
            synchronized (RetrofitManager.class) {
                if (mOkHttpClient == null) {

                    // 指定缓存路径,缓存大小100Mb
                    Cache cache = new Cache(new File(context.getCacheDir(), "HttpCache"),
                            1024 * 1024 * 100);

                    //初始化OkHttpClient
                    mOkHttpClient = new OkHttpClient.Builder()
                            .cache(cache)
                            .addInterceptor(interceptor)
                            .retryOnConnectionFailure(true)
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .addNetworkInterceptor(mTokenInterceptor)
//                            .addInterceptor(new ReadCookiesInterceptor())
//                            .addInterceptor(new SaveCookiesInterceptor())
                            .authenticator(mAuthenticator)
                            .build();

                }
            }
        }
    }

    public void setBaseURL(String baseURL) {
        BaseURL = baseURL;
    }

    private static RetrofitManager instance;

    public static RetrofitManager getInstance() {
        if (instance == null) {
            synchronized (RetrofitManager.class) {
                if (instance == null) {
                    instance = new RetrofitManager();
                }
            }
        }
        return instance;
    }

    public <T> T get(Class<T> tClass) {
        return build().create(tClass);
    }

//    @SuppressWarnings("unchecked")
//    public <T> T getProxy(Class<T> tClass) {
//        T t = build().create(tClass);
//        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class<?>[]{tClass}, new ProxyHandler(t));
//    }

}
